package com.jeesite.modules.stock.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.stock.dao.StockLogoDao;
import com.jeesite.modules.stock.entity.StockLogoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class StockLogoService {

    @Value("${file-server.path}")
    protected String fileServerPath;

    @Autowired
    private Environment env;

    @Autowired
    private StockLogoDao stockLogoDao;

    @Value("${oss.domain}")
    private String ossDomain;

    private static final Map<String, String> exchageLogoPreCodeMap = new HashMap<String, String>() {{
        put("深圳证券交易所", "szse-component-index--big");
        put("北京证券交易所", "bjs");
        put("上海证券交易所", "sse-composite--big");

        put("2", "szse-component-index--big");
        put("3", "bjs");
        put("1", "sse-composite--big");
    }};

    private String getExchageLogo(String exchange) {
        StockLogoEntity logoEntity = stockLogoDao.getLogoByStockCode(exchageLogoPreCodeMap.get(exchange));
        if (logoEntity != null) {
            return logoEntity.getLogo();
        }
        return null;
    }

    /**
     * 处理股票Logo, 拼装完整http地址，如果logo为空则取对应的交易所的logo
     *
     * @param logo     logo
     * @param exchange 交易所
     * @return Http完整Logo链接
     */
    public String getLogoUrl(String stockCode, String logo, String exchange) {
        String activeProfile = env.getActiveProfiles()[0];
        String clogo = logo;
        if (clogo != null && clogo.startsWith("http")) {
            return clogo;
        }
        if ("prod".equals(activeProfile)) {
            if ((StringUtils.isBlank(clogo) || "null".equals(clogo)) && (!StringUtils.isBlank(exchange))) {
                clogo = getExchageLogo(exchange);
            }
            String fileServerPathMirr = fileServerPath.trim();
            if (!fileServerPathMirr.endsWith("/")) {
                fileServerPathMirr += "/";
            }
            return fileServerPathMirr + "logo/" + clogo;
        } else {
            return ossDomain + "/stocks/logos/" + stockCode + ".svg";
        }
    }

    public void saveLogo() {
        try (InputStream inputstream = this.getClass().getClassLoader()
                .getResourceAsStream("stock_logo_mapping.json")) {
            if (inputstream != null) {
                byte[] b = new byte[1024];
                int len;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                while ((len = inputstream.read(b)) > -1) {
                    bout.write(b, 0, len);
                }
                bout.flush();
                String content = bout.toString();
                JSONObject json = JSON.parseObject(content);
                for (String key : json.keySet()) {
                    String value = json.getString(key);
                    StockLogoEntity entity = new StockLogoEntity();
                    entity.setStockCode(key);
                    entity.setLogo(value);
                    stockLogoDao.saveOrUpdate(entity);
                }
            }
        } catch (IOException e) {
            log.error("保存logo失败, errMsg:{}", e.getMessage(), e);
        }
    }
}
